package com.kele.user.controller;

import com.kele.common.model.response.Result;
import com.kele.common.model.response.ResultObject;
import com.kele.model.user.LoginForm;
import com.kele.model.user.User;
import com.kele.model.user.UserDTO;
import com.kele.user.service.UserService;
import com.kele.utils.JwtUtils;
import com.kele.utils.PhoneFormatCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisTemplate redisTemplate;


    @GetMapping("sendSms/{phone}")
    public Result sendSmsCode(@PathVariable String phone){

        if(!PhoneFormatCheckUtils.isPhoneLegal(phone)){
            return new Result(false,"0","手机号不合法");
        }

        return userService.sendSmsCode(phone);
    }

    @GetMapping("getSmsCodeTTL/{phone}")
    public Result getSmsCodeTTL(@PathVariable String phone){
        return userService.getSmsCodeTTL(phone);
    }

    @PostMapping("reg")
    public Result reg(@RequestBody UserDTO userDTO){

        String password = userDTO.getPassword();
        String checkPassword = userDTO.getCheckPassword();
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(checkPassword)){
            return new Result(false,"0","密码为空");
        }
        if(!password.equals(checkPassword)){
            return new Result(false,"0","两次输入密码不一致");
        }

        String smsCode = userDTO.getSmsCode();

        User user = new User();
        user.setPhone(userDTO.getPhone());
        user.setPassword(userDTO.getPassword());
        user.setEmail(userDTO.getEmail());
        user.setCreated(new Date());
        user.setUpdated(new Date());

        return userService.insert(user,smsCode);
    }

    @PostMapping("login")
    public ResultObject<Map> login(@RequestBody LoginForm loginForm){

        String uuid = loginForm.getUuid();
        String code = loginForm.getCode();

        //1.判断code是否正确
        if(!StringUtils.isEmpty(uuid)){
            String redis_code = (String)redisTemplate.opsForValue().get(ImageController.prefix + uuid);
            if(StringUtils.isEmpty(redis_code)){
                return new ResultObject(false,"0","Code失效",null);
            }
            if(!redis_code.equalsIgnoreCase(code)){
                return new ResultObject(false,"0","Code 输入错误",null);
            }
        }
        String password = loginForm.getPassword();
        String username = loginForm.getUsername();//phone email

        //根据phone 或者 email查询是否有用户
        User user = userService.getUserByPhoneOrEmail(username, username);
        if(user==null){
            return new ResultObject(false,"0","用户名或者密码错误",null);
        }
        String passwordEncode = user.getPassword();

        //3 判断密码是否匹配
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(password, passwordEncode);
        if(!matches){
            return new ResultObject(false,"0","用户名或者密码错误",null);
        }

        String token = JwtUtils.createToken(user.getId().toString(),
                username,
                "",
                null);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("userid",user.getId());
        map.put("username",username);

        redisTemplate.opsForValue().set("token_" + token,"aaaa",30, TimeUnit.HOURS);

        return new ResultObject(true,"1", "登陆成功",map);
    }
}
